<template>
  <div class="yy-inspection-content">
    <!--列表-->
    <div class="yy-put-in-manage-list" v-show="type=='list'">
      <Card>
        <p slot="title">
          <Icon type="md-list" />
          巡检内容列表
        </p>
        <Form ref="formInline" :model="formSearch"  inline  class="print-no-show">
          <FormItem prop="user">
            <Select class="select" v-model="formSearch.dcNum" placeholder="请选择设备类别">
              <Option value="">请选择</Option>
              <Option v-for="(item,index) in equipmentCategory" :value="item.dcNum" :key="index">{{item.dcName}}</Option>
            </Select>
          </FormItem>
          <FormItem prop="user">
            <Input type="text" v-model="formSearch.ditName" placeholder="巡检内容名称"></Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSearch()">查询</Button>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleAddBuy()">新增</Button>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handlePrint()">打印</Button>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleExecl()">导出</Button>
          </FormItem>
        </Form>
        <Table :columns="columns" :data="data" ></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
              <Page :total="page.total" :page-size="page.pageSize" :current="1" @on-change="changePage" show-total></Page>
          </div>
        </div>
      </Card>
    </div>

    <!--详情-->
    <div class="yy-put-in-manage-details" v-show="type=='details'">
       <Card>
        <p slot="title">
          <template> 
            <Icon type="md-paper"/>查看详情
          </template>
        </p>
        <p slot="extra">
          <Button type="primary" @click="handlePrint()" style="margin-right:10px">打印</Button>
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="details">
          <p class="details-title"><span>巡检内容编码:</span>{{currentData.dcNum}}</p>
          <p class="details-title"><span>巡检内容名称:</span>{{currentData.dicName}}</p>
          <p class="details-title"><span>设备分类:</span>{{currentData.dcName}}</p>
          <p class="details-title"><span>备注:</span>{{currentData.remark}}</p>
          <p class="details-title"><span>物品列表:</span></p>
        </div>
        <Divider>物品列表</Divider>
        <Table :columns="columnsDetailsList" :data="detailsList" height=200 ></Table>
      </Card>
    </div>

    <!--添加--编辑-->
    <div class="yy-put-in-manage-add-edit"  v-show="(type=='addBuy' || type=='edit')">
      <Card>
        <p slot="title">
          <template v-if="type=='addBuy'"> 
            <Icon type="md-create"/>新增巡检内容
          </template>
          <template v-if="type=='edit'"> 
            <Icon type="md-create"/>编辑巡检内容
          </template>
        </p>
        <p slot="extra" >
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="postForm">
          <Form ref="formInlineA" :model="formSearch"  inline>
            <FormItem>
              <template> 
                <Button type="primary" @click="handleAddBuyGoods()">添加巡检项目</Button>
              </template>
            </FormItem>
          </Form>
          <template> 
            <Divider>已选项目</Divider>
            <Table :columns="columnsA" :data="dataA" height=300></Table>
          </template>
          <br/>        
          <div class="editForm">
            <Form ref="formInventory" :model="formInventory" :rules="checkFormInventory" :label-width="80" @keydown.native.enter.prevent ="createInventory">
              <FormItem label="巡检内容编码"  prop="dicNum" v-if="type=='edit'">
                <Input type="text" v-model="formInventory.dicNum" class="inputWidth" disabled placeholder="请输入制单人"></Input>
              </FormItem>
              <FormItem prop="dcNum" label="设备分类">
                <Select class="select" v-model="formInventory.dcNum" placeholder="请选择设备分类">
                  <Option value="">请选择</Option>
                  <Option v-for="(item,index) in equipmentCategory" :value="item.dcNum" :key="index">{{item.dcName}}</Option>
                </Select>
              </FormItem>
              <FormItem label="巡检内容名称"  prop="dicName">
                <Input type="text" v-model="formInventory.dicName" class="inputWidth" placeholder="请输入制单人"></Input>
              </FormItem>
              <FormItem label="备注"  prop="remark">
                <Input v-model="formInventory.remark" type="textarea" class="inputWidth" :autosize="{minRows: 2,maxRows: 5}" placeholder="备注" maxlength="50"></Input>
              </FormItem>
              <FormItem>
                <Button @click="createInventory()" type="primary" class="button">提交</Button>
                <Button @click="goBack()" type="primary" class="button">取消</Button>
              </FormItem>
            </Form>
          </div>
        </div>
      </Card>
    </div>

    <!--采购添加物品-->
    <Modal
      v-model="modalAddBuy"
      transfer=false
      title="选择采购入库物品"
      @on-ok="ok"
      @on-cancel="cancel"
      width="1000"
      scrollable=true
      footer-hide=true
      >
      <p slot="header" >
        采购入库物品
      </p>
      
      <div class="modalAddBuyGoods">
        <Form :model="formSearchB"  inline>
          <FormItem prop="dcNum">
            <Select class="select" v-model="formSearchB.dcNum" placeholder="请选择设备分类">
              <Option value="">请选择</Option>
              <Option v-for="(item,index) in equipmentCategory" :value="item.dcNum" :key="index">{{item.dcName}}</Option>
            </Select>
          </FormItem>
          <FormItem prop="dicName">
            <Input type="text" v-model="formSearchB.dicName" class="inputWidth" placeholder="请输巡检内容名称"></Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleBuyGoodsSearch()">查询</Button>
          </FormItem>
        </Form>

        <Table :columns="columnsB" :data="dataB" size="small"></Table>

        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
            <Page :total="pageB.total" :page-size="pageB.pageSize" :current="1" @on-change="changePageB" show-total></Page>
          </div>
        </div>
          
        <Divider>完善已添加的物品属性</Divider>
        <div class="modalAddBuyGoodsEdit">
          <CheckboxGroup v-model="checkGroup">
            <div class="modal-item" v-for="(item,index) in selectGoodsList" :key="item.item">
              <div class="modal-inline-a">
                <Checkbox :label="item.itemNum" :disabled="item.isChecked"><span></span></Checkbox> 
              </div>
              <div class="modal-inline-b">
                <span class="modal-item-unit"><span class="modal-title">设备类型:</span>{{item.dcName}}</span>
                <span class="modal-item-unit"><span class="modal-title">步骤编码:</span>{{item.ditNum}}</span>
                <span class="modal-item-unit"><span class="modal-title">步骤名称:</span>{{item.ditName}}</span>
                <span class="modal-item-unit"><span class="modal-title">步骤参考值:</span>{{item.stValue}}</span>
                <span class="modal-item-unit"><span class="modal-title">参考关系:</span>{{item.relation}}</span>
              </div>
              <div class="modal-inline-c">
                <Button type="error" @click="deleteGoodsList(index)">删除</Button>
              </div>
            </div>
          </CheckboxGroup>
        </div>

        <div class="modal-post">
          <Button @click="handleAddCheckList" type="primary" class="button">确认勾选</Button>
        </div>
        
      </div>
    </Modal>
  </div>
</template>

<script>
import API from "./api";
import ValidatorRule from "@/filters/validator-rule";
import { formatTime } from "@/libs/tools";
import i18n from "./locale";
import billMaterials from "../common/bill-materials/bill-materials";
import mixin from "@/mixin/date-mixin";
import expandRow from "../common/warehouse-order-expand-row-component";
import wareHouseMixin from "../common/warehouse-mixin";

export default {
  name: "yy-inspection-content",
  mixins: [mixin, wareHouseMixin],
  components: {
    billMaterials,
    expandRow
  },
  data() {
    return {
      i18n: i18n,
      currentData: "",
      modalAddBuy: false,
      modalAddAllot: false,
      orderReport: "",
      endTimeOption: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      type: "list",
      page: {
        total: 0,
        pageSize: 20
      },
      pageB: {
        total: 0,
        pageSize: 20
      },
      pageC: {
        total: 0,
        pageSize: 20
      },
      formSearch: {
        dcNum: "",
        ditName: "",
        userID: ""
      },
      auditSearch: {
        auditState: 1,
        auditTime: "",
        auditremark: "",
        userID: "",
        userName: "",
        b_UserRole: ""
      },
      formInventory: {
        dcNum: "",
        dicName: "",
        remark: ""
      },
      checkFormInventory: {
        dcNum: ValidatorRule.select,
        dicName: ValidatorRule.require
      },
      formSearchB: {
        ItemNum: "",
        itemName: "",
        cateName: ""
      },
      formSearchC: {
        orderNum: "",
        st: "",
        et: "",
        outType: ""
      },
      columns: [
        {
          title: "巡检内容编码 ",
          key: "dicNum"
        },
        {
          title: "巡检内容名称 ",
          key: "dicName"
        },
        {
          title: "设备分类",
          key: "dcName"
        },
        {
          title: "创建时间",
          key: "createTime"
        },
        {
          title: "创建人 ",
          key: "createUser"
        },
        {
          title: "备注 ",
          key: "remark"
        },
        {
          title: "操作",
          key: "action",
          width: 200,
          align: "center",
          className: "print-no-show",
          render: (h, params) => {
            let viewAction = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small"
                },
                style: {
                  marginRight: "5px"
                },
                on: {
                  click: () => {
                    this.details(params.index);
                  }
                }
              },
              "查看"
            );

            let editAction = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small"
                },
                style: {
                  marginRight: "5px"
                },
                on: {
                  click: () => {
                    this.edit(params.index);
                  }
                }
              },
              "编辑"
            );

            let deleteAction = h(
              "Button",
              {
                props: {
                  type: "error",
                  size: "small"
                },
                style: {
                  marginRight: "5px"
                },
                on: {
                  click: () => {
                    this.delete(params.index, params.row.id);
                  }
                }
              },
              "删除"
            );
            //根据角色判断操作按钮的显示
            let arr = [viewAction, editAction, deleteAction];
            return h("div", arr);
          }
        }
      ],
      data: [],
      columnsA: [
        {
          title: "设备类型",
          key: "dcName"
        },
        {
          title: "步骤编码",
          key: "ditNum"
        },
        {
          title: "步骤名称",
          key: "ditName"
        },
        {
          title: "步骤参考值",
          key: "remark"
        },
        {
          title: "报警关系",
          key: "relation"
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.deleteInventoryGood(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      dataA: [],
      columnsB: [
        {
          title: "设备类型",
          key: "dcName"
        },
        {
          title: "步骤编码",
          key: "ditNum"
        },
        {
          title: "步骤名称",
          key: "ditName"
        },
        {
          title: "步骤参考值",
          key: "remark"
        },
        {
          title: "报警关系",
          key: "relation"
        },
        {
          title: "操作",
          key: "action",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Icon",
                {
                  props: {
                    type: "md-cart",
                    size: "20",
                    color: "#5158d4"
                  },
                  style: {
                    marginRight: "5px",
                    cursor: "pointer"
                  },
                  on: {
                    click: () => {
                      this.addGoods(params.row);
                    }
                  }
                },
                ""
              )
            ]);
          }
        }
      ],
      dataB: [],
      columnsC: [
        {
          type: "expand",
          width: 50,
          render: (h, params) => {
            return h(expandRow, {
              props: {
                list: params.row.list
              }
            });
          }
        },
        {
          title: "出库单号",
          key: "orderNum"
        },
        {
          title: "出库类型",
          key: "outType",
          render: (h, params) => {
            return h("span", this.generateOutType(params.row.outType));
          }
        },
        {
          title: "材料员名称",
          key: "contactName"
        },
        {
          title: "材料员电话",
          key: "phone"
        },
        {
          title: "创建时间",
          key: "createTime"
        },
        {
          title: "审核时间",
          key: "auditTime"
        },
        {
          title: "制单人",
          key: "createUserName"
        },
        {
          title: "备注",
          key: "remark"
        },
        {
          title: "操作",
          key: "action",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Icon",
                {
                  props: {
                    type: "md-cart",
                    size: "20",
                    color: "#5158d4"
                  },
                  style: {
                    marginRight: "5px",
                    cursor: "pointer"
                  },
                  on: {
                    click: () => {
                      this.addAllotGoods(params.row);
                    }
                  }
                },
                ""
              )
            ]);
          }
        }
      ],
      dataC: [],
      dataCateName: [],
      selectGoodsList: [],
      selectAllotGoodsList: [],
      generateInTypeArr: [],
      generateOutTypeArr: [],
      checkGroup: [],
      columnsDetailsList: [
        {
          title: "设备类型",
          key: "dcName"
        },
        {
          title: "步骤编码",
          key: "ditNum"
        },
        {
          title: "步骤名称",
          key: "ditName"
        },
        {
          title: "步骤参考值",
          key: "remark"
        },
        {
          title: "报警关系",
          key: "relation"
        }
      ],
      detailsList: [],
      checkAllotGroup: [],
      equipmentCategory: []
    };
  },

  mounted() {
    this.userInfo = this.$store.state.user.userInfo;
    this.initEquipmentCategory(), this.handleSearch();
  },

  computed: {},

  methods: {
    initEquipmentCategory() {
      let obj = {
        userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getEquipmentCategory(obj);
    },

    //获取设备类别
    getEquipmentCategory(obj) {
      API.getEquipmentCategory(obj)
        .then(res => {
          if (res.code == 200) {
            let dataLoc = res.data;
            this.equipmentCategory = dataLoc.list;
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    handleSearch() {
      let obj = this.formSearch;
      obj.pageNum = 1;
      obj.pageSize = this.page.pageSize;
      this.formSearch = obj;
      this.getList(obj);
    },

    getList(obj) {
      API.getList(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            if (data != null) {
              this.page.total = data.total;
              this.page.pageSize = data.pageSize;
              this.data = data.list;
            } else {
              this.$Message.success({ content: "暂无数据！" });
              this.data = [];
            }
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    changePage(pageNum) {
      let obj = this.formSearch,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearch = obj;
      this.getList(obj);
    },

    goBack() {
      this.type = "list";
    },

    handleAddBuy() {
      this.type = "addBuy";
      this.$refs.formInventory.resetFields();
      this.dataA = [];
      this.formInventory.single = this.userInfo.userName;
      this.formInventory.time = new Date();
    },

    details(index) {
      this.type = "details";
      this.currentData = _.clone(this.data[index]);
      let obj = {
        dicNum: this.data[index].dicNum
      };
      this.getDetailsList(obj);
    },

    getDetailsList(obj) {
      API.getDetailsList(obj)
        .then(res => {
          if (res.code == 200) {
            let dataDet = res.data;
            if (this.type == "details") {
              this.detailsList = dataDet.list;
            } else {
              this.dataA = dataDet.list;
            }
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    edit(index) {
      this.type = "edit";
      this.formInventory = _.clone(this.data[index]);
      let obj = {
        dicNum: this.data[index].dicNum
      };
      this.getDetailsList(obj);
    },

    delete(index, id) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除这条记录",
        onOk: function() {
          let obj = {
            ID: id,
            UserID: tthis.userInfo.userId
          };
          API.delete(obj)
            .then(res => {
              if (res.code == 200) {
                this.$Message.success({ content: "该记录已经删除成功！" });
                tthis.data.splice(index, 1);
                tthis.resetList();
              }
            })
            .catch(err => {
              console.log(err);
              this.$Message.error("请求异常！");
            });
        }
      });
    },

    resetList() {
      //求余为1，页码为最大页码，请求页需减1
      let maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      let remainderNum = this.page.total % this.page.pageSize;
      if (
        this.formSearch.pageNum == maxPageNum &&
        remainderNum == 1 &&
        this.formSearch.pageNum !== 1
      ) {
        this.formSearch.pageNum = this.formSearch.pageNum - 1;
      }
      let obj = this.formSearch;
      this.getList(obj);
    },

    checking(index) {
      this.details(index);
      this.type = "audit";
    },

    handleAudit() {
      let obj = this.auditSearch;
      obj.auditTime = new Date();
      this.audit(obj);
    },

    handleAddBuyGoods() {
      this.modalAddBuy = true;
      this.checkGroup = [];
      //this.selectGoodsList = [];
      if (this.dataB) {
        this.handleBuyGoodsSearch();
      }
    },

    handleBuyGoodsSearch() {
      let obj = this.formSearchB;
      obj.pageNum = 1;
      obj.pageSize = this.pageB.pageSize;
      this.formSearchB = obj;
      this.getGoodsTypeList(obj);
    },

    getGoodsTypeList(obj) {
      API.getGoodsTypeList(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            this.pageB.total = data.total;
            this.pageB.pageSize = data.pageSize;
            this.dataB = data.list;
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    changePageB(pageNum) {
      let obj = this.formSearchB,
        maxPageNum = Math.ceil(this.pageB.total / this.pageB.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearchB = obj;
      this.getGoodsTypeList(obj);
    },

    addGoods(obj) {
      let bool = false,
        gId = obj.id,
        arr = this.selectGoodsList;

      this.$set(obj, "isChecked", true);

      _.forEach(arr, function(value) {
        if (value.id == gId) {
          bool = true;
        }
      });

      if (!bool) {
        arr.push(obj);
        this.checkGroup.push(this.selectGoodsList[obj.index]);
      } else {
        this.$Message.warning("该类型已经添加过了");
      }
      this.selectGoodsList = arr;
      //console.log("addGoods", this.selectGoodsList);
    },

    deleteGoodsList(index) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除?",
        onOk: function() {
          _.forEach(tthis.checkGroup, function(value, key) {
            if (value == good.orderNum) {
              tthis.checkGroup.splice(key, 1);
            }
          });
          tthis.selectGoodsList.splice(index, 1);
        }
      });
    },

    handleAddCheckList() {
      let arr = this.checkGroup;
      if (arr.length > 0) {
        for (let i in arr) {
          let obj = _.find(this.selectGoodsList, function(o) {
            return o.itemNum == arr[i];
          });
          this.dataA.push(obj);
        }
        this.modalAddBuy = false;
        console.log("确认勾选！", this.dataA);
      } else {
        this.$Message.warning("请选择采购的物品.");
      }
    },

    deleteInventoryGood(index) {
      this.dataA.splice(index, 1);
      this.checkGroup.splice(index, 1);
      this.selectGoodsList.splice(index, 1);
    },

    createInventory() {
      this.$refs.formInventory.validate(valid => {
        if (valid) {
          if (this.type == "addBuy" || this.type == "edit") {
            if (this.dataA.length > 0) {
              let obj = {
                dcNum: this.formInventory.dcNum,
                dicName: this.formInventory.dicName,
                remark: this.formInventory.remark,
                list: this.dataA
                //todo 其他参数
              };
              API.saveInventory(obj)
                .then(res => {
                  if (res.code == 200) {
                    this.$Message.success("添加成功！");
                    //提交以后重置表单
                    this.$refs.formInventory.resetFields();
                    this.dataA = [];
                    this.formInventory.single = this.userInfo.userName;
                    this.formInventory.time = new Date();
                    //回到List页面，重新请求
                    (this.selectGoodsList = []), (this.type = "list");
                    this.getList(this.formSearch);
                  }
                })
                .catch(err => {
                  this.$Message.error("请求异常！");
                });
            } else {
              this.$Message.warning("请选择采购的物品.");
            }
          }
        } else {
          this.$Message.warning("请选择填写完清单.");
        }
      });
    },

    handlePrint() {
      window.print();
    },

    handleExecl() {
      alert("后台直接导出EXECL文件！");
    }
  }
};
</script>
<style lang="less" >
@import "./yy-inspection-content.less";
</style>
